"""
报告生成服务
负责AI智能报告生成、模板管理和报告导出功能
"""
import os
import json
import asyncio
import aiofiles
from typing import Dict, Any, List, Optional, Union
from datetime import datetime, timedelta
from pathlib import Path
from enum import Enum
import logging
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc, func

from models.report import Report, ReportTemplate, ReportStatus, ReportFormat, ReportType
from models.analysis_task import AnalysisTask
from models.user import User
from core.database import get_db
from core.logging_config import get_logger
from core.exceptions import ReportError, ValidationError
from services.ai_service_factory import ai_service_factory, ServiceType, create_service_request
# from services.statistics_service import statistics_service, StatsDimension  # 已删除统计服务
from services.data_source_manager import data_source_manager

logger = get_logger("report_service")


class ReportGenerator:
    """报告生成器"""
    
    def __init__(self):
        self.output_dir = Path("reports")
        self.output_dir.mkdir(exist_ok=True)
        self.template_dir = Path("templates")
        self.template_dir.mkdir(exist_ok=True)
    
    async def generate_report(self, db: Session, report_id: int) -> bool:
        """生成报告"""
        try:
            # 获取报告信息
            report = db.query(Report).filter(Report.id == report_id).first()
            if not report:
                raise ReportError(f"报告不存在: {report_id}")
            
            # 更新状态为生成中
            report.start_generation()
            db.commit()
            
            start_time = datetime.now()
            
            # 准备报告数据
            report_data = await self._prepare_report_data(db, report)
            
            # 生成报告内容
            if report.format == ReportFormat.PDF:
                await self._generate_pdf_report(report, report_data)
            elif report.format == ReportFormat.WORD:
                await self._generate_word_report(report, report_data)
            elif report.format == ReportFormat.EXCEL:
                await self._generate_excel_report(report, report_data)
            elif report.format == ReportFormat.HTML:
                await self._generate_html_report(report, report_data)
            else:
                raise ReportError(f"不支持的报告格式: {report.format}")
            
            # 计算生成时间
            generation_time = (datetime.now() - start_time).total_seconds()
            
            # 完成报告生成
            file_path = self.output_dir / report.file_name
            report.complete_generation(str(file_path), report.file_name, generation_time)
            db.commit()
            
            logger.info(f"报告生成完成: {report.title} (ID: {report_id})")
            return True
            
        except Exception as e:
            logger.error(f"报告生成失败: {str(e)}")
            
            # 更新报告状态为失败
            report = db.query(Report).filter(Report.id == report_id).first()
            if report:
                report.fail_generation(str(e))
                db.commit()
            
            raise ReportError(f"报告生成失败: {str(e)}")
    
    async def _prepare_report_data(self, db: Session, report: Report) -> Dict[str, Any]:
        """准备报告数据"""
        try:
            report_data = {
                "title": report.title,
                "description": report.description,
                "report_type": report.report_type,
                "generated_at": datetime.now().isoformat(),
                "time_range": {
                    "start_date": report.start_date.isoformat() if report.start_date else None,
                    "end_date": report.end_date.isoformat() if report.end_date else None
                },
                "data_sources": [],
                "statistics": {},
                "analysis_results": [],
                "charts": []
            }
            
            # 获取数据源信息
            if report.data_source_ids:
                for source_id in report.data_source_ids:
                    source = await data_source_manager.get_data_source_info(source_id)
                    if source:
                        report_data["data_sources"].append(source)
            
            # 获取统计分析数据
            if report.task_ids:
                for task_id in report.task_ids:
                    task_stats = await self._get_task_statistics(db, task_id)
                    if task_stats:
                        report_data["statistics"][f"task_{task_id}"] = task_stats
            
            # 获取总体统计
            filters = {}
            if report.start_date:
                filters["start_date"] = report.start_date
            if report.end_date:
                filters["end_date"] = report.end_date
            if report.region_filter:
                filters.update(report.region_filter)
            if report.pollution_type_filter:
                filters.update(report.pollution_type_filter)
            
            # 基础统计 - 临时禁用，原统计服务已删除
            # basic_stats = statistics_service.get_basic_statistics(db, None, filters)
            # report_data["statistics"]["basic"] = basic_stats

            # 时间序列统计 - 临时禁用，原统计服务已删除
            # time_series = statistics_service.get_time_series_statistics(db, None, None, filters)
            # report_data["statistics"]["time_series"] = time_series

            # 污染类型统计 - 临时禁用，原统计服务已删除
            # pollution_stats = statistics_service.get_pollution_type_statistics(db, None, filters)
            # report_data["statistics"]["pollution_types"] = pollution_stats

            # 区域统计 - 临时禁用，原统计服务已删除
            # regional_stats = statistics_service.get_region_statistics(db, None, filters)
            # report_data["statistics"]["regional"] = regional_stats

            # 临时添加空数据
            report_data["statistics"]["basic"] = {}
            report_data["statistics"]["time_series"] = []
            report_data["statistics"]["pollution_types"] = {}
            report_data["statistics"]["regional"] = {}
            
            # 获取分析结果
            analysis_results = self._get_analysis_results(db, report)
            report_data["analysis_results"] = analysis_results
            
            # AI智能分析
            if report.ai_prompt:
                ai_analysis = await self._generate_ai_analysis(report_data, report.ai_prompt)
                report_data["ai_analysis"] = ai_analysis
            
            return report_data
            
        except Exception as e:
            logger.error(f"准备报告数据失败: {str(e)}")
            raise ReportError(f"准备报告数据失败: {str(e)}")
    
    async def _get_task_statistics(self, db: Session, task_id: int) -> Optional[Dict[str, Any]]:
        """获取任务统计信息"""
        try:
            task = db.query(AnalysisTask).filter(AnalysisTask.id == task_id).first()
            if not task:
                return None
            
            return {
                "task_id": task.id,
                "task_name": task.name,
                "status": task.status,
                "progress": task.progress,
                "total_count": task.total_count,
                "success_count": task.success_count,
                "failed_count": task.failed_count,
                "created_at": task.created_at.isoformat(),
                "start_time": task.start_time.isoformat() if task.start_time else None,
                "end_time": task.end_time.isoformat() if task.end_time else None,
                "duration": task.duration
            }
            
        except Exception as e:
            logger.error(f"获取任务统计失败: {str(e)}")
            return None
    
    def _get_analysis_results(self, db: Session, report: Report) -> List[Dict[str, Any]]:
        """获取分析结果"""
        try:
            query = db.query(AnalysisResult)
            
            # 时间过滤
            if report.start_date:
                query = query.filter(AnalysisResult.created_at >= report.start_date)
            if report.end_date:
                query = query.filter(AnalysisResult.created_at <= report.end_date)
            
            # 任务过滤
            if report.task_ids:
                query = query.filter(AnalysisResult.task_id.in_(report.task_ids))
            
            results = query.order_by(desc(AnalysisResult.created_at)).limit(100).all()
            
            return [result.to_dict() for result in results]
            
        except Exception as e:
            logger.error(f"获取分析结果失败: {str(e)}")
            return []
    
    async def _generate_ai_analysis(self, report_data: Dict[str, Any], prompt: str) -> Dict[str, Any]:
        """生成AI智能分析"""
        try:
            # 构建分析请求数据
            analysis_request = {
                "report_data": report_data,
                "analysis_prompt": prompt,
                "request_type": "report_analysis"
            }
            
            # 创建AI服务请求
            request = create_service_request(
                ServiceType.REPORT_GENERATION,
                analysis_request,
                {"model": "gpt-4", "temperature": 0.7}
            )
            
            # 处理请求
            result = await ai_service_factory.process_request(request)
            
            if result.success:
                return result.data
            else:
                logger.warning(f"AI分析生成失败: {result.error}")
                return {"error": result.error, "fallback_analysis": self._generate_fallback_analysis(report_data)}
            
        except Exception as e:
            logger.error(f"AI分析生成异常: {str(e)}")
            return {"error": str(e), "fallback_analysis": self._generate_fallback_analysis(report_data)}
    
    def _generate_fallback_analysis(self, report_data: Dict[str, Any]) -> Dict[str, Any]:
        """生成备用分析"""
        try:
            basic_stats = report_data.get("statistics", {}).get("basic", {})
            
            analysis = {
                "summary": f"本报告共分析了 {basic_stats.get('total_count', 0)} 条信访数据",
                "key_findings": [
                    f"今日新增信访 {basic_stats.get('today_count', 0)} 条",
                    f"本周新增信访 {basic_stats.get('week_count', 0)} 条",
                    f"本月新增信访 {basic_stats.get('month_count', 0)} 条"
                ],
                "trends": "数据呈现稳定趋势",
                "recommendations": [
                    "建议持续关注信访数据变化",
                    "加强重点区域的管理",
                    "优化信访处理流程"
                ]
            }
            
            return analysis
            
        except Exception as e:
            logger.error(f"生成备用分析失败: {str(e)}")
            return {"summary": "数据分析失败", "key_findings": [], "trends": "未知", "recommendations": []}
    
    async def _generate_pdf_report(self, report: Report, report_data: Dict[str, Any]):
        """生成PDF报告"""
        try:
            # 这里使用HTML转PDF的方式
            html_content = await self._generate_html_content(report, report_data)
            
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_name = f"report_{report.id}_{timestamp}.pdf"
            file_path = self.output_dir / file_name
            
            # 使用weasyprint或类似库生成PDF
            # 这里暂时保存HTML内容，实际项目中需要集成PDF生成库
            html_file = self.output_dir / f"report_{report.id}_{timestamp}.html"
            async with aiofiles.open(html_file, 'w', encoding='utf-8') as f:
                await f.write(html_content)
            
            # 临时设置文件名，实际项目中需要生成PDF
            report.file_name = file_name
            
            logger.info(f"PDF报告生成完成: {file_name}")
            
        except Exception as e:
            logger.error(f"PDF报告生成失败: {str(e)}")
            raise ReportError(f"PDF报告生成失败: {str(e)}")
    
    async def _generate_word_report(self, report: Report, report_data: Dict[str, Any]):
        """生成Word报告"""
        try:
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_name = f"report_{report.id}_{timestamp}.docx"
            file_path = self.output_dir / file_name
            
            # 使用python-docx库生成Word文档
            # 这里暂时创建一个简单的Word文档结构
            from docx import Document
            from docx.shared import Inches
            
            doc = Document()
            
            # 标题
            doc.add_heading(report.title, 0)
            
            # 描述
            if report.description:
                doc.add_paragraph(report.description)
            
            # 生成时间
            doc.add_paragraph(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            # 基础统计
            doc.add_heading('基础统计', level=1)
            basic_stats = report_data.get("statistics", {}).get("basic", {})
            doc.add_paragraph(f"总数量: {basic_stats.get('total_count', 0)}")
            doc.add_paragraph(f"今日数量: {basic_stats.get('today_count', 0)}")
            doc.add_paragraph(f"本周数量: {basic_stats.get('week_count', 0)}")
            doc.add_paragraph(f"本月数量: {basic_stats.get('month_count', 0)}")
            
            # AI分析
            ai_analysis = report_data.get("ai_analysis", {})
            if ai_analysis:
                doc.add_heading('AI智能分析', level=1)
                if "summary" in ai_analysis:
                    doc.add_paragraph(f"摘要: {ai_analysis['summary']}")
                
                if "key_findings" in ai_analysis:
                    doc.add_heading('主要发现', level=2)
                    for finding in ai_analysis["key_findings"]:
                        doc.add_paragraph(f"• {finding}")
                
                if "recommendations" in ai_analysis:
                    doc.add_heading('建议', level=2)
                    for recommendation in ai_analysis["recommendations"]:
                        doc.add_paragraph(f"• {recommendation}")
            
            # 保存文档
            doc.save(str(file_path))
            report.file_name = file_name
            
            logger.info(f"Word报告生成完成: {file_name}")
            
        except Exception as e:
            logger.error(f"Word报告生成失败: {str(e)}")
            raise ReportError(f"Word报告生成失败: {str(e)}")
    
    async def _generate_excel_report(self, report: Report, report_data: Dict[str, Any]):
        """生成Excel报告"""
        try:
            import pandas as pd
            
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_name = f"report_{report.id}_{timestamp}.xlsx"
            file_path = self.output_dir / file_name
            
            # 创建Excel写入器
            with pd.ExcelWriter(str(file_path), engine='openpyxl') as writer:
                # 基础统计
                basic_stats = report_data.get("statistics", {}).get("basic", {})
                if basic_stats:
                    stats_df = pd.DataFrame([
                        {"指标": "总数量", "数值": basic_stats.get('total_count', 0)},
                        {"指标": "今日数量", "数值": basic_stats.get('today_count', 0)},
                        {"指标": "本周数量", "数值": basic_stats.get('week_count', 0)},
                        {"指标": "本月数量", "数值": basic_stats.get('month_count', 0)}
                    ])
                    stats_df.to_excel(writer, sheet_name='基础统计', index=False)
                
                # 污染类型统计
                pollution_stats = report_data.get("statistics", {}).get("pollution_types", {})
                if pollution_stats and "main_types" in pollution_stats:
                    chart_data = pollution_stats["main_types"].get("chart_data", {})
                    if chart_data and "labels" in chart_data and "datasets" in chart_data:
                        labels = chart_data["labels"]
                        data = chart_data["datasets"][0]["data"]
                        
                        pollution_df = pd.DataFrame({
                            "污染类型": labels,
                            "数量": data
                        })
                        pollution_df.to_excel(writer, sheet_name='污染类型统计', index=False)
                
                # 区域统计
                regional_stats = report_data.get("statistics", {}).get("regional", {})
                if regional_stats and "district_distribution" in regional_stats:
                    chart_data = regional_stats["district_distribution"].get("chart_data", {})
                    if chart_data and "labels" in chart_data and "datasets" in chart_data:
                        labels = chart_data["labels"]
                        data = chart_data["datasets"][0]["data"]
                        
                        regional_df = pd.DataFrame({
                            "区域": labels,
                            "数量": data
                        })
                        regional_df.to_excel(writer, sheet_name='区域统计', index=False)
                
                # 分析结果
                analysis_results = report_data.get("analysis_results", [])
                if analysis_results:
                    results_df = pd.DataFrame(analysis_results)
                    results_df.to_excel(writer, sheet_name='分析结果', index=False)
            
            report.file_name = file_name
            
            logger.info(f"Excel报告生成完成: {file_name}")
            
        except Exception as e:
            logger.error(f"Excel报告生成失败: {str(e)}")
            raise ReportError(f"Excel报告生成失败: {str(e)}")
    
    async def _generate_html_report(self, report: Report, report_data: Dict[str, Any]):
        """生成HTML报告"""
        try:
            html_content = await self._generate_html_content(report, report_data)
            
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_name = f"report_{report.id}_{timestamp}.html"
            file_path = self.output_dir / file_name
            
            # 保存HTML文件
            async with aiofiles.open(file_path, 'w', encoding='utf-8') as f:
                await f.write(html_content)
            
            report.file_name = file_name
            
            logger.info(f"HTML报告生成完成: {file_name}")
            
        except Exception as e:
            logger.error(f"HTML报告生成失败: {str(e)}")
            raise ReportError(f"HTML报告生成失败: {str(e)}")
    
    async def _generate_html_content(self, report: Report, report_data: Dict[str, Any]) -> str:
        """生成HTML内容"""
        try:
            # 获取模板内容
            template_content = ""
            if report.template_id:
                template = db.query(ReportTemplate).filter(ReportTemplate.id == report.template_id).first()
                if template and template.template_content:
                    template_content = template.template_content
            
            # 如果没有模板，使用默认模板
            if not template_content:
                template_content = self._get_default_html_template()
            
            # 准备模板数据
            template_data = {
                "title": report.title,
                "description": report.description or "",
                "generated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "statistics": report_data.get("statistics", {}),
                "ai_analysis": report_data.get("ai_analysis", {}),
                "analysis_results": report_data.get("analysis_results", [])
            }
            
            # 简单的模板替换
            html_content = template_content.replace("{{title}}", template_data["title"])
            html_content = html_content.replace("{{description}}", template_data["description"])
            html_content = html_content.replace("{{generated_at}}", template_data["generated_at"])
            
            # 替换统计数据
            basic_stats = template_data["statistics"].get("basic", {})
            html_content = html_content.replace("{{total_count}}", str(basic_stats.get("total_count", 0)))
            html_content = html_content.replace("{{today_count}}", str(basic_stats.get("today_count", 0)))
            html_content = html_content.replace("{{week_count}}", str(basic_stats.get("week_count", 0)))
            html_content = html_content.replace("{{month_count}}", str(basic_stats.get("month_count", 0)))
            
            # 替换AI分析
            ai_analysis = template_data.get("ai_analysis", {})
            if "summary" in ai_analysis:
                html_content = html_content.replace("{{ai_summary}}", ai_analysis["summary"])
            else:
                html_content = html_content.replace("{{ai_summary}}", "暂无AI分析")
            
            return html_content
            
        except Exception as e:
            logger.error(f"生成HTML内容失败: {str(e)}")
            raise ReportError(f"生成HTML内容失败: {str(e)}")
    
    def _get_default_html_template(self) -> str:
        """获取默认HTML模板"""
        return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { border-bottom: 2px solid #333; padding-bottom: 10px; margin-bottom: 20px; }
        .section { margin-bottom: 30px; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; }
        .stat-card { border: 1px solid #ddd; padding: 15px; border-radius: 5px; }
        .stat-value { font-size: 24px; font-weight: bold; color: #007bff; }
        .analysis { background-color: #f8f9fa; padding: 20px; border-radius: 5px; }
    </style>
</head>
<body>
    <div class="header">
        <h1>{{title}}</h1>
        <p>{{description}}</p>
        <p>生成时间: {{generated_at}}</p>
    </div>
    
    <div class="section">
        <h2>基础统计</h2>
        <div class="stats-grid">
            <div class="stat-card">
                <div>总数量</div>
                <div class="stat-value">{{total_count}}</div>
            </div>
            <div class="stat-card">
                <div>今日数量</div>
                <div class="stat-value">{{today_count}}</div>
            </div>
            <div class="stat-card">
                <div>本周数量</div>
                <div class="stat-value">{{week_count}}</div>
            </div>
            <div class="stat-card">
                <div>本月数量</div>
                <div class="stat-value">{{month_count}}</div>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>AI智能分析</h2>
        <div class="analysis">
            <h3>摘要</h3>
            <p>{{ai_summary}}</p>
        </div>
    </div>
</body>
</html>
        """


class ReportTemplateManager:
    """报告模板管理器"""
    
    def __init__(self):
        self.template_dir = Path("templates")
        self.template_dir.mkdir(exist_ok=True)
    
    def create_template(self, db: Session, template_data: Dict[str, Any], creator_id: int) -> ReportTemplate:
        """创建报告模板"""
        try:
            template = ReportTemplate(
                name=template_data["name"],
                description=template_data.get("description", ""),
                report_type=template_data["report_type"],
                format=template_data["format"],
                category=template_data.get("category", "default"),
                template_content=template_data.get("template_content", ""),
                template_config=template_data.get("template_config", {}),
                field_mapping=template_data.get("field_mapping", {}),
                ai_prompt_template=template_data.get("ai_prompt_template", ""),
                ai_model_config=template_data.get("ai_model_config", {}),
                style_config=template_data.get("style_config", {}),
                chart_config=template_data.get("chart_config", {}),
                creator_id=creator_id,
                is_system=template_data.get("is_system", False),
                sort_order=template_data.get("sort_order", 0)
            )
            
            db.add(template)
            db.commit()
            db.refresh(template)
            
            logger.info(f"报告模板创建成功: {template.name} (ID: {template.id})")
            return template
            
        except Exception as e:
            logger.error(f"创建报告模板失败: {str(e)}")
            raise ReportError(f"创建报告模板失败: {str(e)}")
    
    def update_template(self, db: Session, template_id: int, update_data: Dict[str, Any]) -> Optional[ReportTemplate]:
        """更新报告模板"""
        try:
            template = db.query(ReportTemplate).filter(ReportTemplate.id == template_id).first()
            if not template:
                return None
            
            # 更新字段
            if "name" in update_data:
                template.name = update_data["name"]
            if "description" in update_data:
                template.description = update_data["description"]
            if "report_type" in update_data:
                template.report_type = update_data["report_type"]
            if "format" in update_data:
                template.format = update_data["format"]
            if "category" in update_data:
                template.category = update_data["category"]
            if "template_content" in update_data:
                template.template_content = update_data["template_content"]
            if "template_config" in update_data:
                template.template_config = update_data["template_config"]
            if "field_mapping" in update_data:
                template.field_mapping = update_data["field_mapping"]
            if "ai_prompt_template" in update_data:
                template.ai_prompt_template = update_data["ai_prompt_template"]
            if "ai_model_config" in update_data:
                template.ai_model_config = update_data["ai_model_config"]
            if "style_config" in update_data:
                template.style_config = update_data["style_config"]
            if "chart_config" in update_data:
                template.chart_config = update_data["chart_config"]
            if "sort_order" in update_data:
                template.sort_order = update_data["sort_order"]
            
            db.commit()
            db.refresh(template)
            
            logger.info(f"报告模板更新成功: {template.name} (ID: {template_id})")
            return template
            
        except Exception as e:
            logger.error(f"更新报告模板失败: {str(e)}")
            raise ReportError(f"更新报告模板失败: {str(e)}")
    
    def delete_template(self, db: Session, template_id: int) -> bool:
        """删除报告模板"""
        try:
            template = db.query(ReportTemplate).filter(ReportTemplate.id == template_id).first()
            if not template:
                return False
            
            # 检查是否有报告使用此模板
            reports_count = db.query(Report).filter(Report.template_id == template_id).count()
            if reports_count > 0:
                raise ReportError(f"无法删除模板，已有 {reports_count} 个报告使用此模板")
            
            db.delete(template)
            db.commit()
            
            logger.info(f"报告模板删除成功: {template.name} (ID: {template_id})")
            return True
            
        except Exception as e:
            logger.error(f"删除报告模板失败: {str(e)}")
            raise ReportError(f"删除报告模板失败: {str(e)}")
    
    def get_template(self, db: Session, template_id: int) -> Optional[ReportTemplate]:
        """获取报告模板"""
        try:
            return db.query(ReportTemplate).filter(ReportTemplate.id == template_id).first()
        except Exception as e:
            logger.error(f"获取报告模板失败: {str(e)}")
            return None
    
    def list_templates(self, db: Session, filters: Dict[str, Any] = None, 
                      page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取模板列表"""
        try:
            query = db.query(ReportTemplate)
            
            # 应用过滤条件
            if filters:
                if "report_type" in filters:
                    query = query.filter(ReportTemplate.report_type == filters["report_type"])
                if "format" in filters:
                    query = query.filter(ReportTemplate.format == filters["format"])
                if "category" in filters:
                    query = query.filter(ReportTemplate.category == filters["category"])
                if "creator_id" in filters:
                    query = query.filter(ReportTemplate.creator_id == filters["creator_id"])
                if "is_system" in filters:
                    query = query.filter(ReportTemplate.is_system == filters["is_system"])
                if "is_active" in filters:
                    query = query.filter(ReportTemplate.is_active == filters["is_active"])
            
            # 获取总数
            total = query.count()
            
            # 分页
            templates = query.order_by(ReportTemplate.sort_order, ReportTemplate.created_at.desc()).offset(
                (page - 1) * page_size
            ).limit(page_size).all()
            
            return {
                "total": total,
                "page": page,
                "page_size": page_size,
                "items": [template.to_dict() for template in templates]
            }
            
        except Exception as e:
            logger.error(f"获取模板列表失败: {str(e)}")
            raise ReportError(f"获取模板列表失败: {str(e)}")
    
    def create_default_templates(self, db: Session):
        """创建默认模板"""
        try:
            default_templates = [
                {
                    "name": "标准信访分析报告",
                    "description": "标准格式的信访数据分析报告",
                    "report_type": ReportType.SUMMARY,
                    "format": ReportFormat.HTML,
                    "category": "标准报告",
                    "template_content": self._get_standard_html_template(),
                    "is_system": True,
                    "sort_order": 1
                },
                {
                    "name": "详细统计报告",
                    "description": "包含详细统计分析的报告",
                    "report_type": ReportType.DETAILED,
                    "format": ReportFormat.PDF,
                    "category": "详细报告",
                    "template_content": self._get_detailed_html_template(),
                    "is_system": True,
                    "sort_order": 2
                },
                {
                    "name": "数据统计报表",
                    "description": "以数据表格为主的统计报表",
                    "report_type": ReportType.STATISTICAL,
                    "format": ReportFormat.EXCEL,
                    "category": "统计报表",
                    "is_system": True,
                    "sort_order": 3
                }
            ]
            
            for template_data in default_templates:
                # 检查是否已存在
                existing = db.query(ReportTemplate).filter(
                    ReportTemplate.name == template_data["name"],
                    ReportTemplate.is_system == True
                ).first()
                
                if not existing:
                    self.create_template(db, template_data, creator_id=1)  # 系统用户ID
            
            logger.info("默认报告模板创建完成")
            
        except Exception as e:
            logger.error(f"创建默认模板失败: {str(e)}")
            raise ReportError(f"创建默认模板失败: {str(e)}")
    
    def _get_standard_html_template(self) -> str:
        """获取标准HTML模板"""
        return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { text-align: center; border-bottom: 3px solid #007bff; padding-bottom: 20px; margin-bottom: 30px; }
        .header h1 { color: #007bff; margin: 0; font-size: 28px; }
        .header p { color: #666; margin: 10px 0 0 0; }
        .section { margin-bottom: 40px; }
        .section h2 { color: #333; border-left: 4px solid #007bff; padding-left: 15px; margin-bottom: 20px; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .stat-card h3 { margin: 0 0 10px 0; font-size: 16px; opacity: 0.9; }
        .stat-card .value { font-size: 32px; font-weight: bold; margin: 0; }
        .analysis { background-color: #f8f9fa; padding: 25px; border-radius: 10px; border-left: 4px solid #28a745; }
        .analysis h3 { color: #28a745; margin-top: 0; }
        .findings ul, .recommendations ul { padding-left: 20px; }
        .findings li, .recommendations li { margin-bottom: 8px; }
        .footer { text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; color: #666; font-size: 14px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{{title}}</h1>
            <p>{{description}}</p>
            <p>生成时间: {{generated_at}}</p>
        </div>
        
        <div class="section">
            <h2>基础统计</h2>
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>总数量</h3>
                    <div class="value">{{total_count}}</div>
                </div>
                <div class="stat-card">
                    <h3>今日数量</h3>
                    <div class="value">{{today_count}}</div>
                </div>
                <div class="stat-card">
                    <h3>本周数量</h3>
                    <div class="value">{{week_count}}</div>
                </div>
                <div class="stat-card">
                    <h3>本月数量</h3>
                    <div class="value">{{month_count}}</div>
                </div>
            </div>
        </div>
        
        <div class="section">
            <h2>AI智能分析</h2>
            <div class="analysis">
                <h3>摘要</h3>
                <p>{{ai_summary}}</p>
            </div>
        </div>
        
        <div class="footer">
            <p>本报告由智能信访分析系统自动生成</p>
        </div>
    </div>
</body>
</html>
        """
    
    def _get_detailed_html_template(self) -> str:
        """获取详细HTML模板"""
        return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }
        .container { max-width: 1400px; margin: 0 auto; background-color: white; padding: 40px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { text-align: center; border-bottom: 3px solid #007bff; padding-bottom: 30px; margin-bottom: 40px; }
        .header h1 { color: #007bff; margin: 0; font-size: 32px; }
        .header p { color: #666; margin: 15px 0 0 0; font-size: 16px; }
        .section { margin-bottom: 50px; }
        .section h2 { color: #333; border-left: 4px solid #007bff; padding-left: 20px; margin-bottom: 25px; font-size: 24px; }
        .section h3 { color: #555; margin-bottom: 15px; font-size: 18px; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 25px; margin-bottom: 40px; }
        .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .stat-card h3 { margin: 0 0 15px 0; font-size: 16px; opacity: 0.9; }
        .stat-card .value { font-size: 36px; font-weight: bold; margin: 0; }
        .chart-container { background-color: #f8f9fa; padding: 30px; border-radius: 10px; margin-bottom: 30px; }
        .analysis { background-color: #e8f5e8; padding: 30px; border-radius: 10px; border-left: 4px solid #28a745; margin-bottom: 30px; }
        .analysis h3 { color: #28a745; margin-top: 0; }
        .data-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .data-table th, .data-table td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        .data-table th { background-color: #f2f2f2; font-weight: bold; }
        .data-table tr:nth-child(even) { background-color: #f9f9f9; }
        .footer { text-align: center; margin-top: 50px; padding-top: 30px; border-top: 1px solid #eee; color: #666; font-size: 14px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{{title}}</h1>
            <p>{{description}}</p>
            <p>生成时间: {{generated_at}}</p>
        </div>
        
        <div class="section">
            <h2>基础统计</h2>
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>总数量</h3>
                    <div class="value">{{total_count}}</div>
                </div>
                <div class="stat-card">
                    <h3>今日数量</h3>
                    <div class="value">{{today_count}}</div>
                </div>
                <div class="stat-card">
                    <h3>本周数量</h3>
                    <div class="value">{{week_count}}</div>
                </div>
                <div class="stat-card">
                    <h3>本月数量</h3>
                    <div class="value">{{month_count}}</div>
                </div>
            </div>
        </div>
        
        <div class="section">
            <h2>AI智能分析</h2>
            <div class="analysis">
                <h3>摘要</h3>
                <p>{{ai_summary}}</p>
            </div>
        </div>
        
        <div class="footer">
            <p>本报告由智能信访分析系统自动生成</p>
        </div>
    </div>
</body>
</html>
        """


class ReportService:
    """报告服务主类"""
    
    def __init__(self):
        self.generator = ReportGenerator()
        self.template_manager = ReportTemplateManager()
    
    async def create_report(self, db: Session, report_data: Dict[str, Any], creator_id: int) -> Report:
        """创建报告"""
        try:
            # 验证模板
            template_id = report_data.get("template_id")
            if template_id:
                template = db.query(ReportTemplate).filter(ReportTemplate.id == template_id).first()
                if not template:
                    raise ValidationError("模板不存在")
                
                # 验证格式匹配
                if template.format != report_data.get("format"):
                    raise ValidationError("报告格式与模板格式不匹配")
            
            # 创建报告
            report = Report(
                title=report_data["title"],
                description=report_data.get("description", ""),
                report_type=report_data["report_type"],
                format=report_data["format"],
                template_id=template_id,
                start_date=report_data.get("start_date"),
                end_date=report_data.get("end_date"),
                data_source_ids=report_data.get("data_source_ids", []),
                task_ids=report_data.get("task_ids", []),
                region_filter=report_data.get("region_filter", {}),
                pollution_type_filter=report_data.get("pollution_type_filter", {}),
                config=report_data.get("config", {}),
                ai_prompt=report_data.get("ai_prompt", ""),
                creator_id=creator_id
            )
            
            db.add(report)
            db.commit()
            db.refresh(report)
            
            logger.info(f"报告创建成功: {report.title} (ID: {report.id})")
            return report
            
        except Exception as e:
            logger.error(f"创建报告失败: {str(e)}")
            raise ReportError(f"创建报告失败: {str(e)}")
    
    async def generate_report(self, db: Session, report_id: int) -> bool:
        """生成报告"""
        return await self.generator.generate_report(db, report_id)
    
    def get_report(self, db: Session, report_id: int) -> Optional[Report]:
        """获取报告"""
        try:
            return db.query(Report).filter(Report.id == report_id).first()
        except Exception as e:
            logger.error(f"获取报告失败: {str(e)}")
            return None
    
    def list_reports(self, db: Session, filters: Dict[str, Any] = None, 
                    page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取报告列表"""
        try:
            query = db.query(Report)
            
            # 应用过滤条件
            if filters:
                if "status" in filters:
                    query = query.filter(Report.status == filters["status"])
                if "report_type" in filters:
                    query = query.filter(Report.report_type == filters["report_type"])
                if "format" in filters:
                    query = query.filter(Report.format == filters["format"])
                if "creator_id" in filters:
                    query = query.filter(Report.creator_id == filters["creator_id"])
                if "start_date" in filters:
                    query = query.filter(Report.created_at >= filters["start_date"])
                if "end_date" in filters:
                    query = query.filter(Report.created_at <= filters["end_date"])
                if "is_active" in filters:
                    query = query.filter(Report.is_active == filters["is_active"])
            
            # 获取总数
            total = query.count()
            
            # 分页
            reports = query.order_by(desc(Report.created_at)).offset(
                (page - 1) * page_size
            ).limit(page_size).all()
            
            return {
                "total": total,
                "page": page,
                "page_size": page_size,
                "items": [report.to_dict() for report in reports]
            }
            
        except Exception as e:
            logger.error(f"获取报告列表失败: {str(e)}")
            raise ReportError(f"获取报告列表失败: {str(e)}")
    
    def delete_report(self, db: Session, report_id: int) -> bool:
        """删除报告"""
        try:
            report = db.query(Report).filter(Report.id == report_id).first()
            if not report:
                return False
            
            # 删除文件
            if report.file_path:
                try:
                    import os
                    if os.path.exists(report.file_path):
                        os.remove(report.file_path)
                except Exception as e:
                    logger.warning(f"删除报告文件失败: {str(e)}")
            
            db.delete(report)
            db.commit()
            
            logger.info(f"报告删除成功: {report.title} (ID: {report_id})")
            return True
            
        except Exception as e:
            logger.error(f"删除报告失败: {str(e)}")
            raise ReportError(f"删除报告失败: {str(e)}")
    
    def publish_report(self, db: Session, report_id: int, published_by: int) -> bool:
        """发布报告"""
        try:
            report = db.query(Report).filter(Report.id == report_id).first()
            if not report:
                return False
            
            if report.status != ReportStatus.COMPLETED:
                raise ValidationError("只能发布已完成的报告")
            
            report.publish(published_by)
            db.commit()
            
            logger.info(f"报告发布成功: {report.title} (ID: {report_id})")
            return True
            
        except Exception as e:
            logger.error(f"发布报告失败: {str(e)}")
            raise ReportError(f"发布报告失败: {str(e)}")
    
    def archive_report(self, db: Session, report_id: int) -> bool:
        """归档报告"""
        try:
            report = db.query(Report).filter(Report.id == report_id).first()
            if not report:
                return False
            
            report.archive()
            db.commit()
            
            logger.info(f"报告归档成功: {report.title} (ID: {report_id})")
            return True
            
        except Exception as e:
            logger.error(f"归档报告失败: {str(e)}")
            raise ReportError(f"归档报告失败: {str(e)}")
    
    def get_report_file(self, db: Session, report_id: int) -> Optional[str]:
        """获取报告文件路径"""
        try:
            report = db.query(Report).filter(Report.id == report_id).first()
            if not report or not report.file_path:
                return None
            
            import os
            if os.path.exists(report.file_path):
                return report.file_path
            
            return None
            
        except Exception as e:
            logger.error(f"获取报告文件失败: {str(e)}")
            return None


# 全局报告服务实例
report_service = ReportService()